package com.luck.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

public class HttpUtil {

    private static Logger logger = Logger.getLogger(HttpUtil.class);

    public static String doGet(String url, Map<String,String> map) {
        HttpGet httpGet = null;
        if (map == null || map.size() == 0) {
            httpGet = new HttpGet(url);
            logger.info("【send】【doGet】无参 url:" + url);
        } else {
            try {
                URIBuilder uriBuilder = new URIBuilder(url);
                map.forEach((k, v) -> {
                    uriBuilder.addParameter(k, v);
                });
                URI build = uriBuilder.build();
                httpGet = new HttpGet(build);
                logger.info("【send】【doGet】有参 url:" + build.toString());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 请求超时时间
                .setSocketTimeout(60000)// 数据读取超时时间
                .build();
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * POST 请求 json
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, String json) {
        logger.info("【send】【doPost】json, url:" + url + ",参数:" + json);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String result = null;
        CloseableHttpResponse response = null;
        try {
            StringEntity stringEntity = new StringEntity(json,"UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            result =  EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * POST 请求 Form
     * @param url
     * @param map
     * @return
     */
    public static String doPostForm(String url, Map<String, String> map) {
        logger.info("【send】【doPost】form, url:" + url + ",参数:" + map);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        map.forEach((k, v) -> {
            BasicNameValuePair basicNameValuePair = new BasicNameValuePair(k, v);
            nameValuePairs.add(basicNameValuePair);
        });
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * POST 请求 Form/上传图片
     * @param url
     * @param map
     * @param file
     * @return
     */
    public static String doPostFormData(String url, Map<String, String> map, MultipartFile file) {
        logger.info("【send】【doPost】formData, url:" + url + ",参数:" + map + "," + file);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        ContentType contentType = ContentType.APPLICATION_JSON;
        entityBuilder.setCharset(contentType.getCharset());
        map.forEach((k, v) -> {
            entityBuilder.addTextBody(k, v, contentType);
        });
        String result = null;
        CloseableHttpResponse response = null;
        try {
            entityBuilder.addBinaryBody(file.getName(), file.getBytes(), ContentType.create("multipart/form-data"), file.getName());
            httpPost.setEntity(entityBuilder.build());
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * POST 请求 无规则字符
     * @param url
     * @param text
     * @return
     */
    public static String doPostText(String url, String text) {
        logger.info("【send】【doPost】Text, url:" + url + ",参数:" + text);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        ContentType contentType = ContentType.create("text/plain", "UTF-8");
        StringEntity stringEntity = new StringEntity(text, contentType);
        stringEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 根据url 返回 byte[]
     * @param url
     * @return
     * @throws IOException
     */
    public static byte[] UrlGetBytes(String url) {
        URLConnection urlConnection;
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        byte[] byteArray = null;
        try {
            urlConnection = new URL(url).openConnection();
            inputStream = urlConnection.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int n;
            while (-1 != (n = inputStream.read(bytes))) {
                outputStream.write(bytes, 0, n);
            }
            byteArray = outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArray;
    }

    /**
     * 将url 内容保存到 本地路径
     * @param url
     * @param path
     * @return
     * @throws IOException
     */
    public static boolean UrlSaveToPath(String path, String url) {
        byte[] bytes = HttpUtil.UrlGetBytes(url);
        return HttpUtil.BytesSaveToPath(path, bytes);
    }

    /**
     * 将bytes 内容保存到 本地路径
     * @param path
     * @param bytes
     * @return
     */
    public static boolean BytesSaveToPath(String path, byte[] bytes) {
        if (StringUtils.isEmpty(path) || bytes == null || bytes.length == 0) {
            return false;
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            fileOutputStream.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}
